package org.example.demo1;


import com.google.gson.Gson;
import dao.StudentDao;
import pojo.Student;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;

@WebServlet(name = "Up", value = "/updata")
public class Updata extends HelloServlet {
//    根据学生姓名和id修改学生的电话号码
    public void doPost(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        request.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
//        一样创造一个StringBuilder()对象用来读去存储的json数据
         StringBuilder sb = new StringBuilder();
//        使用request中的getReader获取请求的输入流
         BufferedReader reader = request.getReader();
String line;
while ((line=reader.readLine())!=null){
    sb.append(line);
}
//将储存的json数据转换成字符串
         String string = sb.toString();
//创造gson对象
         Gson gson = new Gson();
         Student s2 = gson.fromJson(string, Student.class);
        System.out.println(s2.toString());

         StudentDao studentDao = new StudentDao();
         int flag = studentDao.updata(s2);
         HashMap<String, Object> hs = new HashMap<>();
        if (flag>0){
            hs.put("code", 200);
            hs.put("msg", "更新成功");
            hs.put("data", 1);
        }else {
            hs.put("code", 500);
            hs.put("msg", "更新失败");
            hs.put("data", 0);
        }
         String json = gson.toJson(hs);
        resp.getWriter().println(json);


    }
}
